<template>
  <table-manage>
    <!-- 表格操作 -->
    <template #search>
      <el-form-item label="班级名称">
        <el-input placeholder="请输入班级名称" v-model:model-value="pageParam.searchObject.updateNo"/>
      </el-form-item>
      <el-form-item label="年级">
        <el-select v-model:model-value="pageParam.searchObject.platformName" placeholder="请选择年级">
          <el-option label="高一" value="高一"/>
          <el-option label="高二" value="高二"/>
          <el-option label="高三" value="高三"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" type="primary" @click="loadTableData">搜索</el-button>
        <el-button :icon="RefreshRight" @click="resetSearchForm">重置</el-button>
      </el-form-item>
    </template>

    <template #operate>
      <el-button :icon="Plus" type="primary" @click="onAdd">添加班级</el-button>
      <el-button :icon="Upload" type="success" @click="importStudents">导入学生</el-button>
    </template>

    <!-- 表格视图 -->
    <template #default>
      <el-table stripe row-key="id" :data="pageVo.records">
        <el-table-column prop="updateNo" label="班级名称" width="150"/>
        <el-table-column prop="platformName" label="年级" width="120"/>
        <el-table-column prop="updateDesc" label="班主任" width="120"/>
        <el-table-column prop="studentCount" label="学生人数" width="120"/>
        <el-table-column prop="averageScore" label="平均成绩" width="120"/>
        <el-table-column prop="downloadUrl" label="班级口号" show-overflow-tooltip/>
        <el-table-column prop="createTime" label="创建时间" width="180"/>
        <el-table-column prop="updateTime" label="更新时间" width="180"/>
        <!-- 单行操作 -->
        <el-table-column fixed="right" width="280" label="操作">
          <template #default="scope">
            <el-button :icon="View" size="small" type="success" @click="viewStudents(scope.row)">查看学生</el-button>
            <el-button :icon="Edit" size="small" @click="onEdit(scope.row)">编辑</el-button>
            <el-button :icon="DeleteFilled" size="small" plain type="danger" @click="onRemove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template #page>
      <el-pagination background layout="total, sizes, prev, pager, next, jumper"
                     :total="pageVo.total" :page-size="pageVo.pageSize" :page-sizes=[10,20,50,100]
                     @current-change="onPageChange" @size-change="onSizeChange"/>
    </template>

    <!-- 编辑对话框 -->
    <template #form>
      <el-dialog v-model="dialogFormVisible" :title="`${editForm.id? '编辑' : '添加'}班级`" width="600px">
        <el-form ref="sttFormRef" label-width="120px" :model="editForm" :rules="rules">
          <el-form-item prop="updateNo" label="班级名称">
            <el-input v-model="editForm.updateNo" placeholder="如：1班、2班"></el-input>
          </el-form-item>
          <el-form-item prop="platformName" label="年级">
            <el-select v-model="editForm.platformName" placeholder="请选择年级">
              <el-option label="高一" value="高一"/>
              <el-option label="高二" value="高二"/>
              <el-option label="高三" value="高三"/>
            </el-select>
          </el-form-item>
          <el-form-item prop="updateDesc" label="班主任">
            <el-input v-model="editForm.updateDesc"></el-input>
          </el-form-item>
          <el-form-item prop="studentCount" label="学生人数">
            <el-input-number v-model="editForm.studentCount" :min="0" :max="100" placeholder="请输入学生人数"></el-input-number>
          </el-form-item>
          <el-form-item prop="averageScore" label="平均成绩">
            <el-input-number v-model="editForm.averageScore" :min="0" :max="100" placeholder="请输入平均成绩"></el-input-number>
          </el-form-item>
          <el-form-item prop="downloadUrl" label="班级口号">
            <el-input v-model="editForm.downloadUrl" type="textarea" rows="3" placeholder="请输入班级口号"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="doUpdate(sttFormRef)">确认</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 查看学生对话框 -->
      <el-dialog v-model="dialogStudentsVisible" title="班级学生列表" width="800px">
        <el-table :data="studentsList" stripe style="width: 100%">
          <el-table-column prop="name" label="姓名" width="120"/>
          <el-table-column prop="studentId" label="学号" width="150"/>
          <el-table-column prop="gender" label="性别" width="80"/>
          <el-table-column prop="phone" label="联系电话" width="150"/>
          <el-table-column prop="address" label="家庭住址"/>
        </el-table>
      </el-dialog>
    </template>
  </table-manage>
</template>

<script setup lang="ts">
import {onMounted, ref, reactive, nextTick} from "vue";
import {add, deleteBatch, update, listByPage} from "@/api/system/sys-version-api";
import {reqCommonFeedback, reqSuccessFeedback} from "@/api/ApiFeedback";
import TableManage from "@/components/container/TableManage.vue";
import {ElForm} from "element-plus/es";
import {ElMessage, ElMessageBox} from "element-plus";
import {DeleteFilled, Plus, Search, RefreshRight, Edit, View, Upload} from "@element-plus/icons-vue";

type FormInstance = InstanceType<typeof ElForm>
const sttFormRef = ref<FormInstance>();

const pageParam = ref<PageParam>({pageNo: 1, pageSize: 20, searchObject: {}});
// 表单参数
const editForm = ref<VersionModel>({});
// 加载进度
const loading = ref<boolean>(true);
// 表单校验规则
const rules = reactive({
  updateNo: [{required: true, message: '请输入班级名称', trigger: 'blur'}],
  platformName: [{required: true, message: '请选择年级', trigger: 'change'}],
  updateDesc: [{required: true, message: '请输入班主任姓名', trigger: 'blur'}],
});

const dialogFormVisible = ref<boolean>(false);
const dialogStudentsVisible = ref<boolean>(false);
const pageVo = ref<PageVO>({pageNo: 1, pageSize: 20, total: 0, records: []});
const studentsList = ref([
  {
    name: '张三',
    studentId: '20240001',
    gender: '男',
    phone: '13800138000',
    address: '北京市海淀区'
  },
  {
    name: '李四',
    studentId: '20240002',
    gender: '女',
    phone: '13800138001',
    address: '北京市朝阳区'
  }
]);

// 初始化数据
onMounted(() => {
  loadTableData();
});

const onEdit = (row: DictionaryModel): void => {
  editForm.value = row;
  dialogFormVisible.value = true;
}

const onAdd = () => {
  dialogFormVisible.value = true;
  editForm.value = {};
}

const onRemove = (row: DictionaryModel): void => {
  ElMessageBox.confirm('确认删除此班级?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    reqSuccessFeedback(deleteBatch([row.id]), '删除成功', () => {
      loadTableData();
    });
  });
}

const loadTableData = (): void => {
  if (!loading.value) loading.value = true;
  let param = {
    pageNo: pageParam.value.pageNo,
    pageSize: pageParam.value.pageSize,
    sysVersion: pageParam.value.searchObject
  };
  reqCommonFeedback(listByPage(param), (data: any) => {
    pageVo.value = data;
    loading.value = false;
  });
}

const onPageChange = (currentPage: number) => {
  pageParam.value.pageNo = currentPage;
  nextTick(() => loadTableData());
}

const onSizeChange = (size: number) => {
  pageParam.value.pageSize = size;
  nextTick(() => loadTableData());
}

const doUpdate = (formEl: FormInstance | undefined): void => {
  if (!formEl) return;
  formEl.validate((valid: boolean) => {
    if (valid) {
      if (!editForm.value.id) {
        reqSuccessFeedback(add(editForm.value), '新增班级成功', () => {
          loadTableData();
          dialogFormVisible.value = false;
        });
      } else {
        reqSuccessFeedback(update(editForm.value), '修改班级成功', () => {
          loadTableData();
          dialogFormVisible.value = false;
        });
      }
    }
  });
}

const resetSearchForm = () => {
  pageParam.value.searchObject = {};
}

const viewStudents = (row: any) => {
  dialogStudentsVisible.value = true;
  // 这里可以添加获取班级学生列表的API调用
}

const importStudents = () => {
  ElMessage.success('学生导入功能开发中...');
}
</script>

<style scoped>
.el-input-number {
  width: 100%;
}
</style>